//
//  GSCommonLoginVerificationCodeView.m
//  GSLoginDemo
//
//  Created by guoshikeji_a on 2018/7/30.
//  Copyright © 2018年 guoshikeji. All rights reserved.
//

#import "GSCommonLoginVerificationCodeView.h"

#import "GSCommonLoginVerifyCodeTextField.h"
#import "GSCommonLoginVerifyCodeLabel.h"

#define GSCommonLoginVerificationCodeViewLabelBaseTag 1000


#define GSCommonLoginVerificationCodeViewLabelWidth 48.0/2

#define GSCommonLoginVerificationCodeViewLabelLabelPadding 50.0/2

#define GSCommonLoginVerificationCodeViewDefaultHeight 112.0/2

@interface GSCommonLoginVerificationCodeView () <UITextFieldDelegate,GSCommonLoginVerifyCodeTextFieldDelegate> {
    //
    GSCommonLoginVerifyCodeLabel *_currentVerifyCodeLabel;
}

@property (nonatomic, strong) GSCommonLoginVerifyCodeTextField *verifyTextFeild;


/**
 *labels
 */
@property (nonatomic, strong) NSMutableArray *labels;

@end

@implementation GSCommonLoginVerificationCodeView

- (NSMutableArray *)labels {
    if (!_labels) {
        _labels = [NSMutableArray array];
    }
    return _labels;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self setupSubviews];
    }
    return self;
}
- (void)setupSubviews {
    self.verifyTextFeild = [GSCommonLoginVerifyCodeTextField new];
    self.verifyTextFeild.font = [UIFont systemFontOfSize:40 weight:UIFontWeightRegular];
    self.verifyTextFeild.textAlignment = NSTextAlignmentCenter;
    self.verifyTextFeild.delegate = self;
    self.verifyTextFeild.deleteDelegate = self;
    self.verifyTextFeild.keyboardType = UIKeyboardTypeNumberPad;
    [self addSubview:self.verifyTextFeild];
    //
    self.verifyTextFeild.inputAccessoryView = [UIView new];
}

- (void)setVerifyCodeDigits:(NSInteger)verifyCodeDigits {
    _verifyCodeDigits = verifyCodeDigits;
    //
    for (UIView *subView in self.labels) {
        [subView removeFromSuperview];
    }
    [self.labels removeAllObjects];
    UIView *aboveView;
    for (int i=1; i<=verifyCodeDigits; i++) {
        GSCommonLoginVerifyCodeLabel *label = [GSCommonLoginVerifyCodeLabel new];
        label.textAlignment = NSTextAlignmentCenter;
        label.tag = GSCommonLoginVerificationCodeViewLabelBaseTag+i;
        [self addSubview:label];
        if (aboveView) {
            [label mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.bottom.mas_equalTo(self);
                make.width.mas_equalTo(GSCommonLoginVerificationCodeViewLabelWidth);
                make.left.mas_equalTo(aboveView.mas_right).offset(GSCommonLoginVerificationCodeViewLabelLabelPadding);
            }];
        }else {
            [label mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.bottom.mas_equalTo(self);
                make.width.mas_equalTo(GSCommonLoginVerificationCodeViewLabelWidth);
                make.left.mas_equalTo(self);
            }];
        }
        aboveView = label;
        [self.labels addObject:label];
    }
    aboveView = nil;
    if (self.labels.count) {
        _currentVerifyCodeLabel = self.labels[0];
    }
    [self bringSubviewToFront:self.verifyTextFeild];
}

- (void)layoutTextFieldFrame {
    if (_currentVerifyCodeLabel) {
        self.verifyTextFeild.frame = _currentVerifyCodeLabel.frame;
    }else {
        self.verifyTextFeild.frame = CGRectZero;
    }
}

- (void)clearLabelsText {
    for (int i=0; i<self.labels.count; i++) {
        GSCommonLoginVerifyCodeLabel *label = self.labels[i];
        label.text = nil;
        if (i==0) {
            _currentVerifyCodeLabel = label;
        }
    }
}
- (void)beginInputAction {
    [self restartInputAction];
}

- (void)restartInputAction {
    [self clearLabelsText];
    [self.verifyTextFeild becomeFirstResponder];
    //
    [self verifyCodeInputCompletedCheck];
}

- (void)textFeildResignFirstResponder {
    [self.verifyTextFeild resignFirstResponder];
    self.verifyTextFeild.frame = CGRectZero;
}

- (NSString *)verifyCode {
    NSMutableArray *codes = [NSMutableArray arrayWithCapacity:self.labels.count];
    for (int i=0; i<self.labels.count; i++) {
        GSCommonLoginVerifyCodeLabel *label = self.labels[i];
        if (label.text) {
            [codes addObject:label.text];
        }
    }
    NSString *code = [codes componentsJoinedByString:@""];
    if (code.length==self.verifyCodeDigits) {
        return code;
    }else {
        return nil;
    }
}

#pragma mark - 判断是否完成输入
- (void)verifyCodeInputCompletedCheck {
    GSCommonLoginVerifyCodeLabel *lastLb = self.labels.lastObject;
    if (self.verifyCodeComplete) {
        self.verifyCodeComplete(lastLb.text.length);
    }
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    [self layoutTextFieldFrame];
    return true;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if ([@"1234567890" rangeOfString:string].location!=NSNotFound) {
        _currentVerifyCodeLabel.text = string;
        //
        GSCommonLoginVerifyCodeLabel *lastLb = self.labels.lastObject;
        if (lastLb==_currentVerifyCodeLabel) {
            [self textFeildResignFirstResponder];
        }else {
            NSInteger idx = [self.labels indexOfObject:_currentVerifyCodeLabel];
            _currentVerifyCodeLabel = self.labels[idx+1];
            [self layoutTextFieldFrame];
        }
    }
    [self verifyCodeInputCompletedCheck];
    return false;
}

#pragma mark - GSCommonLoginVerifyCodeTextFieldDelegate
//回退
- (void)deleteBackward {
    NSInteger idx = [self.labels indexOfObject:_currentVerifyCodeLabel];
    _currentVerifyCodeLabel.text = nil;
    //
    if (idx!=0) {
        _currentVerifyCodeLabel = self.labels[idx-1];
        _currentVerifyCodeLabel.text = nil;
    }
    [self layoutTextFieldFrame];
    //
    [self verifyCodeInputCompletedCheck];
}


#pragma mark -
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [super touchesBegan:touches withEvent:event];
    //
    GSCommonLoginVerifyCodeLabel *lb = self.labels.lastObject;
    if (lb.text && lb==_currentVerifyCodeLabel) {
        [self restartInputAction];
    }else {
        [self.verifyTextFeild becomeFirstResponder];
    }
}




+ (CGSize)viewSizeWithVerifyCodeDigits:(NSInteger)verifyCodeDigits {
    if (verifyCodeDigits<=0) {
        return CGSizeMake(0, GSCommonLoginVerificationCodeViewDefaultHeight);
    }else if(verifyCodeDigits==1) {
        return CGSizeMake(GSCommonLoginVerificationCodeViewLabelWidth, GSCommonLoginVerificationCodeViewDefaultHeight);
    }else {
        CGFloat width = verifyCodeDigits*GSCommonLoginVerificationCodeViewLabelWidth+(verifyCodeDigits-1)*GSCommonLoginVerificationCodeViewLabelLabelPadding;
        return CGSizeMake(width, GSCommonLoginVerificationCodeViewDefaultHeight);
    }
}

@end
